package com.newhis.utils;

import groovy.lang.GroovyClassLoader;
import org.codehaus.groovy.control.CompilerConfiguration;

import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 业务聚合
 *
 * @version [V2.0]
 * @package com.ruoyi;
 * @description:[用一句话描述该文件做什么]
 * @author: [zhuben]
 * @date: [2023-08-21 16:50]
 * @copyright: 2023 echovin.com
 */

public class GroovyUtil {
    private static final int SPRING_BEAN = 1;
    private static final int SPRIG_CONTROLLER = 2;
    private static GroovyClassLoader groovyClassLoader;
    public static ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();


    static {
        CompilerConfiguration compilerConfiguration = new CompilerConfiguration();
        compilerConfiguration.setSourceEncoding("UTF-8");
        groovyClassLoader = new GroovyClassLoader(Thread.currentThread().getContextClassLoader(), compilerConfiguration);
    }

    /**
     * 加载基础groovy脚本内容
     * @param id
     * @param script
     * @param type 0 普通类 1 springBean注册 2springController注册
     */
    public static void loadScript(String id, String script, int type) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Class o = (Class)map.get(id);
        if (o == null){
            Class aClass = groovyClassLoader.parseClass(script);
            if (type == SPRING_BEAN){
                BeanUtils.createBean(aClass);
            }
            if (type == SPRIG_CONTROLLER){
                BeanUtils.registRequestMapping(aClass);
            }
            map.put(id, aClass);
        }
    }

    /**
     * 修改groovy脚本内容并重新加载
     */
    public static void editScript(String id, String script, int type) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Class o = (Class)map.get(id);
        if (o != null){
            map.remove(id);
        }
        loadScript(id, script, type);
    }

    /**
     * 删除groovy脚本
     * @param id
     */
    public static void delScript(String id, int type) {
        Class o = (Class)map.get(id);
        if (o != null){
            map.remove(id);
            if (type == SPRING_BEAN){
                BeanUtils.removeBean(o);
            }

            if (type == SPRIG_CONTROLLER){
                BeanUtils.unregistRequestMapping(o);
            }
        }
    }
}
